package com.cssy.xxkj.logic.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.basic.entity.BasicWorkshopDO;
import com.cssy.xxkj.basic.service.IBasicUtilService;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.contants.BillTypeConstant;
import com.cssy.xxkj.logic.entity.LogicProductionDailyDO;
import com.cssy.xxkj.logic.entity.LogicProductionDailyItemDO;
import com.cssy.xxkj.logic.entity.LogicProductionDispatchingDetailItemDO;
import com.cssy.xxkj.logic.service.ILogicProdDispatchingDetailService;
import com.cssy.xxkj.logic.service.ILogicProductionDailyService;
import com.cssy.xxkj.logic.util.CommonUtil;
import com.cssy.xxkj.logic.util.OftenMothedUtil;
import com.cssy.yd.logic.util.SqlUtil;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.json.OutJsonGrid;
/**
 * 生产日报控制器
 * @author hf
 *
 */
@Controller
@RequestMapping("/logic/prodaily")
public class ProductionDailyController extends BaseController<LogicProductionDailyDO> {
	
	private static final Logger logger = Logger.getLogger(ProductionDailyController.class);

	private static final String MANAGER = "/xxkj/logic/productiondaily/ProDailyManager";// 列表页面
	private static final String EIDT = "/xxkj/logic/productiondaily/ProDailyOperation";// 添加、修改、显示页面
	
	private static final String EIDTDAILY = "/xxkj/logic/productiondaily/ProDailyBatchOperation";// 添加、修改、显示页面
	//生产日报
	@Resource(name = "logicProductionDailyService")
	private ILogicProductionDailyService logicProductionDailyService;
	//派工详情
	@Resource(name = "logicProdDispatchingDetailService")
	private ILogicProdDispatchingDetailService logicProdDispatchingDetailService;
	
	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;
	
	@Resource(name="basicUtilService")
	private IBasicUtilService basicUtilService;
	
	@Resource(name = "oftenMothedUtil")
	private OftenMothedUtil oftenMothedUtil;
	
	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		scs=this.oftenMothedUtil.getNoFinishConditions(scs, "p.zd008Billstatus", BillStatusUtil.PRODAILY_BILL_STATUS_TWO);
		if(StringUtils.isBlank(scs.getOrderBy())){
			scs.setOrderBy("p.bizCreatorDate desc");
		}
		Map<String,Object> sqlWSHMap = SqlUtil.sqlUtil.roleShSqlFilter(request, scUserRolePlaceService,"zd011WorkShopCode");
		List<String> workShopCodeList = (List<String>)sqlWSHMap.get("roleShList");
		scs.addCondition("pm.zd028WorkShop",basicUtilService.resultWorkshopIdList(workShopCodeList, new SearchConditions()));
		SearchResult result = logicProductionDailyService.findListByRoleExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);

	}
	
	

	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
			throws Exception {
		if (OperationFlag.ADD.equals(flag)) {// 新增加时操作
			model.addAttribute("flag", "ADD");
		} else {
			LogicProductionDailyDO daily = logicProductionDailyService.findListById(id);
			model.addAttribute("daily", daily);
		}
		return EIDT;
	}
	
	@RequestMapping(value = "/operatedaily")
	public String operationDaily(HttpServletRequest request, HttpServletResponse response) throws Exception{
		return EIDTDAILY;
	}
	
	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicProductionDailyDO prodispat = logicProductionDailyService.findListById(id);
			List<LogicProductionDailyItemDO> soitem = logicProductionDailyService.findDispatItemList(prodispat.getId());
			OutJsonGrid out = new OutJsonGrid(soitem);
			out.printJSon(response);
		}
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicProductionDailyDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String itemdata = request.getParameter("itemdata");
			if (StringUtils.isBlank(itemdata)) {
				bodyMap.isFail();
				bodyMap.configWebInfor("产品列表不能为空！");
				return bodyMap.modelMap;
			}
			logicProductionDailyService.dailySave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields = ids.split(",");
			for (String field : fields) {
				LogicProductionDailyDO ld = logicProductionDailyService.findListById(field);
				logicProductionDailyService.deleteBizRemoved(ld.getId());
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
			
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	/**
	 * 取得派工详情
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/gridDetailItems")
	public void gridBomItems(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("detailId", id);
			List<LogicProductionDispatchingDetailItemDO> detailItemList = logicProdDispatchingDetailService.findItemListByMap(paramMap);
			List<LogicProductionDailyItemDO> dailyList = this.dispatchingDetailToDaily(detailItemList);
			OutJsonGrid out = new OutJsonGrid(dailyList);
			out.printJSon(response);
		}
	}
	
	@RequestMapping("/detaillist")
	public void detaillist(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions dScs = new SearchConditions();
		hander.getWheres(dScs);
		dScs.addCondition("zd008WorkStatus", BillStatusUtil.PRODISPATDTL_BILL_STATUS_ZERO, SearchCondition.OP_EQUAL);
		Map<String,Object> sqlWSHMap = SqlUtil.sqlUtil.roleShSqlFilter(request, scUserRolePlaceService,"zd011WorkShopCode");
		dScs.addCondition(sqlWSHMap.get("option")+"",(List<String>)sqlWSHMap.get("roleShList"));
		SearchResult result = logicProdDispatchingDetailService.findListByExample(dScs);
		OutJsonGrid out=new OutJsonGrid(result);
		out.printJSon(response);
	}
	
	/**
	 * 组装生产日报
	 * @param detailItemList
	 * @return
	 * @throws Exception
	 */
	private List<LogicProductionDailyItemDO> dispatchingDetailToDaily(List<LogicProductionDispatchingDetailItemDO> detailItemList) throws Exception{
		List<LogicProductionDailyItemDO> dailylist = new ArrayList<LogicProductionDailyItemDO>();
		if(detailItemList==null||detailItemList.isEmpty()||detailItemList.size()==0){
			return dailylist;
		}
		for(LogicProductionDispatchingDetailItemDO detailItem : detailItemList){
			if(detailItem==null||StringUtils.isBlank(detailItem.getId())){
				continue;
			}
			LogicProductionDailyItemDO dailyItem = new LogicProductionDailyItemDO();
			dailyItem.setZd003CustomerId(detailItem.getZd003CustomerId());
			dailyItem.setZd004CustomerCode(detailItem.getZd004CustomerCode());
			dailyItem.setZd005CustomerName(detailItem.getZd005CustomerName());
			dailyItem.setZd006MaterialsId(detailItem.getZd001DetailId());
			dailyItem.setZd006MaterialsCode(detailItem.getZd006MaterialsCode());
			dailyItem.setZd006MaterialsName(detailItem.getZd006MaterialsName());
			dailyItem.setZd007UseCode(detailItem.getZd007UseCode());
			dailyItem.setZd008UseName(detailItem.getZd008UseName());
			dailyItem.setZd009MaterialsBatch(detailItem.getZd009MaterialsBatch());
			dailyItem.setZd010MaterialsModel(detailItem.getZd010MaterialsModel());
			dailyItem.setZd011MaterialsSpec(detailItem.getZd011MaterialsSpec());
			dailyItem.setZd012MaterialsUnit(detailItem.getZd012MaterialsUnit());
			dailyItem.setZd014Price(detailItem.getZd014Price());
			dailyItem.setZd015DeliveryDate(detailItem.getZd015DeliveryDate());
			BigDecimal dispQuantity = detailItem.getZd013Quantity()==null?BigDecimal.ZERO:detailItem.getZd013Quantity();
			BigDecimal backQuantity = detailItem.getZd019ReturnQuantity()==null?BigDecimal.ZERO:detailItem.getZd019ReturnQuantity();
			dailyItem.setZd016ProductionQuantity(dispQuantity.subtract(backQuantity));
			dailyItem.setZd017StorageQuantity(detailItem.getZd017StorageQuantity());
			dailyItem.setZd018OutboundQuantity(detailItem.getZd018OutboundQuantity());
			dailyItem.setZd019ReturnQuantity(backQuantity);
			dailyItem.setZd020Remark(detailItem.getZd020Remark());
			dailyItem.setZd021MaterialsDescription(detailItem.getZd021MaterialsDescription());
			dailyItem.setZd022OpenBatch(detailItem.getZd022OpenBatch());
			dailyItem.setZd023MaterialsSize(detailItem.getZd023MaterialsSize());
			dailyItem.setZd024MaterialsPicture(detailItem.getZd024MaterialsPicture());
			dailyItem.setZd025MaterialsAnnex(detailItem.getZd025MaterialsAnnex());
			dailyItem.setZd026MaterialsColor(detailItem.getZd026MaterialsColor());
			dailyItem.setZd027MaterialsQuality(detailItem.getZd027MaterialsQuality());
			dailyItem.setZd028WorkShop(detailItem.getZd028WorkShop());
			dailyItem.setZd028WorkShopName(detailItem.getZd028WorkShopName());
			dailyItem.setZd029Process(detailItem.getZd029Process());
			dailyItem.setZd029ProcessName(detailItem.getZd029ProcessName());
			dailyItem.setZd030DispatQuantity(dispQuantity);
			dailylist.add(dailyItem);
		}
		return dailylist;
	}
	
	@RequestMapping(value = "/pldailyToSave")
	@ResponseBody
	public Map<String,String> pldailyToSave(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		Map<String, String> map=new HashMap<String, String>();
		try{
			String detailIdStr = request.getParameter("detailIdStr");
			String flagMark = request.getParameter("flagMark");
			List<String> detailIdList = CommonUtil.splitIds(detailIdStr);
			logicProductionDailyService.pldailyToSave(request, detailIdList, flagMark);
			map.put("errorMsg", "SUCCESS");
		}catch(Exception e){
			e.printStackTrace();
			map.put("errorMsg", "ERROR");
		}
		return map;
	}
	
	
}
